package com.kangaroo.myhome.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.kangaroo.myhome.Exception.CustomException;
import com.kangaroo.myhome.Exception.CustomExceptionType;
import com.kangaroo.myhome.model.TSUserloginInfo;
import com.kangaroo.myhome.service.impl.UserLoginInfoService;
import com.kangaroo.myhome.vo.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.kangaroo.myhome.security.JwtAuthenticatioToken;
import com.kangaroo.myhome.utils.SecurityUtils;
import com.kangaroo.myhome.vo.HttpResult;
import com.kangaroo.myhome.vo.LoginBean;
import tk.mybatis.mapper.util.StringUtil;

/**
 * @Description: 功能描述: //
 * @author: kangaroo
 * @date: 2020/7/31 0:02
 */
@RestController
public class LoginController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserLoginInfoService userLoginInfoService;

    /**
     * 登录接口
     */
    @PostMapping(value = "/login")
    public HttpResult login(@RequestBody LoginBean loginBean, HttpServletRequest request) {
        String username = loginBean.getUsername();
        String password = loginBean.getPassword();
        JwtAuthenticatioToken token = null;
        try {
            // 系统登录认证
            token = SecurityUtils.login(request, username, password, authenticationManager);

        } catch (Exception exception) {
            throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "用户名或者密码错误");
        }

        TSUserloginInfo tSUserloginInfo = new TSUserloginInfo();
        tSUserloginInfo.setWorkNo(username);
        tSUserloginInfo.setIp(request.getLocalAddr());
        userLoginInfoService.saveLoginInfo(tSUserloginInfo);

        return HttpResult.ok(token);
    }

    /**
     * 登录接口
     */
    @PostMapping(value = "/loginOut")
    public ResponseModel loginOut() {
        SecurityUtils.loginOut();
        return new ResponseModel();
    }

}